// import { onMounted, onBeforeUnmount } from "vue";
import { eventBus } from "../utils/eventBus";

const useDrag = () => {
  let retry = 0;
  let x = 0,
    y = 0,
    scale = 1,
    minScale = 1,
    maxScale = 3;
  let pointsRelativePos = [];
  function eventsInit({ baseMaps, container, points }) {
    let lastPointermove = { x: 0, y: 0 };
    let isBaseMapDragging = false;
    baseMaps.forEach(baseMap => {
      baseMap.addEventListener("pointerdown", baseMapMouseDownEvent);

      baseMap.addEventListener("pointermove", documentMousemoveEvent);

      // 鼠标抬起，停止拖拽
      baseMap.addEventListener("pointerup", documentMouseupEvent);
    });

    container.addEventListener("wheel", baseMapWheelEvent);

    //点位初始化
    if (points.length > 0) {
      points?.forEach(point => {
        pointsRelativePos.push({
          x: point.style.left - parseInt(baseMaps[0].style.left),
          y: point.style.top - parseInt(baseMaps[0].style.top)
        });
      });
    }

    function baseMapMouseDownEvent(e: PointerEvent) {
      const baseMap = e.target;
      e.preventDefault();
      isBaseMapDragging = true;
      baseMap.setPointerCapture(e.pointerId);
      lastPointermove = { x: e.clientX, y: e.clientY };
    }

    function baseMapWheelEvent(e: WheelEvent) {
      const baseMap = e.target;
      if (!baseMap.className.includes("base-map")) return;
      e.preventDefault();
      let ratio = 1.1;
      let preScale = scale < minScale ? minScale : scale;
      if (e.deltaY > 0) {
        ratio = 1 / 1.1;
      }

      const newScale = Number((scale * ratio).toFixed(4));
      if (newScale > maxScale) {
        scale = maxScale;
      } else if (newScale < minScale) {
        scale = minScale;
      } else {
        scale = newScale;
      }
      if (preScale === scale) return;
      const rect = baseMap.getBoundingClientRect();
      const mouseX = e.clientX - rect.left;
      const mouseY = e.clientY - rect.top;

      // 计算新的偏移量，使图片以鼠标位置为中心进行缩放
      x = mouseX - (mouseX - x) * ratio;
      y = mouseY - (mouseY - y) * ratio;
      //这里是不是改成循环就行
      updateDrawer(baseMap, { x, y });
      // 更新所有 point 位置
    }
    function documentMousemoveEvent(e) {
      const baseMap = e.target;
      if (!baseMap.className.includes("base-map")) return;

      e.preventDefault();
      if (isBaseMapDragging) {
        const diffX = e.clientX - lastPointermove.x;
        const diffY = e.clientY - lastPointermove.y;
        lastPointermove = { x: e.clientX, y: e.clientY };
        x += diffX;
        y += diffY;

        updateDrawer(baseMap, { x, y });
      }
    }
    function documentMouseupEvent() {
      isBaseMapDragging = false;
    }
    const offEvents = () => {
      baseMaps.forEach(baseMap => {
        baseMap.removeEventListener("pointerdown", baseMapMouseDownEvent);
        baseMap.removeEventListener("pointermove", documentMousemoveEvent);
        baseMap.removeEventListener("pointerup", documentMouseupEvent);
      });

      container.removeEventListener("wheel", baseMapWheelEvent);

      retry = 0;
      console.log("useDrag,卸载事件");
    };
    function updateDrawer(baseMap, { x, y }) {
      if (points.length > 0) {
        updatePointsPosition(baseMap, { x, y });
      } else {
        updateBaseMap({ x, y });
      }
    }
    function updateBaseMap({ x, y }) {
      baseMaps.forEach(baseMap => {
        changeStyle("transform", `translate3d(${x}px, ${y}px, 0) scale(${scale})`, baseMap.id);
      });
    }
    function updatePointsPosition(baseMap, { x, y }) {
      points.forEach((point, index) => {
        let dx = (parseFloat(point.style["width"]) * (scale - 1)) / 2;
        let dy = parseFloat(point.style["height"]) * (scale - 1) * 0.5;
        const pointX = x + pointsRelativePos[index].x * scale + parseFloat(baseMap.style.left) + dx;
        const pointY = y + pointsRelativePos[index].y * scale + parseFloat(baseMap.style.top) + dy;

        changeStyle("left", parseFloat(pointX).toFixed(4), point.id);
        changeStyle("top", parseFloat(pointY).toFixed(4), point.id);
      });
      updateBaseMap({ x, y });
    }
    return offEvents;
  }

  async function dragInit(cur) {
    let container = document.getElementsByClassName("middle-content")[0];
    let baseMaps = document.getElementsByClassName("base-map") as any;

    if (container && baseMaps && baseMaps[0] && baseMaps[0].src) {
      baseMaps = Array.from(baseMaps);
      return await new Promise(resolve => {
        const img = new Image();
        img.src = baseMaps[baseMaps.length - 1].src;
        if (img.complete) {
          timeFun();
          console.log("e--->图片缓存加载成功");
        } else {
          img.onload = timeFun;
        }
        function timeFun() {
          setTimeout(() => {
            let points = [];
            let pointStr = "DrillLocation TextLocation ColorLocation RectLocation VLocation DrillLocation2 MessageLocation VText middleTip";
            cur.forEach(dot => {
              const { item } = dot;
              if (pointStr.includes(item.component)) {
                points.push(item);
              }
            });
            const res = eventsInit({ baseMaps, container, points });

            console.log("e--->图片加载完成");
            resolve(res);
          }, 200);
        }
      });
    } else if (retry < 10) {
      retry += 1;
      console.log("重试：", retry);
      return await new Promise(resolve => {
        setTimeout(() => {
          const res = dragInit(cur);
          resolve(res);
        }, 1000);
      });
    } else {
      retry = 0;
      console.log("e--->可视化拖拽初始化失败，或者是这个图片被设置为不可拖拽");
      return false;
    }
  }
  function changeStyle(styleName, value, compId = null) {
    //由直接修改ref改为通知祖先组件修改props数据

    eventBus.emit("changeStyle", { styleName, value, compId });
  }
  return {
    dragInit
  };
};
export default useDrag;
